package com.sendpo.zjx.sendpo.fragment.helpingorder;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.LoginActivity;
import com.sendpo.zjx.sendpo.activity.MyselfHelpingOrderSingleActivity;
import com.sendpo.zjx.sendpo.domain.HelpInfoDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/21.
 */

public class MyselfHelpingorderFragment extends BaseHelpingFragment {


    View rootView = null;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.pulltofresh)
     public PullToRefreshLayout pulltofresh;
    Unbinder unbinder;

    private LinearLayoutManager lm;

    private RecylcerAdaper adpter;
    private int pagenow = 1;
    public int currentlastitem = 0;
    public boolean lastloading = false;

    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_helpingorder_recycler, null);
        ButterKnife.bind(view, mActivity);
        return view;
    }
    public void initData() {
        lm = new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL, false);
        recyclerview.setLayoutManager(lm);
        List<HelpInfoDomain.DataBean> dataBeanList=new ArrayList<>();
        recyclerview.setAdapter(adpter=new RecylcerAdaper(dataBeanList,mActivity));
        pulltofresh.setPullDownEnable(true);
        pulltofresh.setPullUpEnable(true);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pagenow = 1;
                query(pagenow);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                MyselfHelpingorderFragment.this.pagenow++;
                append(MyselfHelpingorderFragment.this.pagenow);
            }
        });
        pulltofresh.autoRefresh();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view

        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, rootView);
            initData();

        }
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();


    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<HelpInfoDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<HelpInfoDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_user_needlistitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final HelpInfoDomain.DataBean dataBean = dataBeen.get(position);
            final IndexHoler ih = (IndexHoler) holder;
            ih.cir_icon.setImageResource(R.drawable.nim_avatar_default);
            Glide.with(MyselfHelpingorderFragment.this)
                    .load(dataBean.getUserAvatarpath())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .animate(R.anim.fade_in)
                    .placeholder(R.drawable.nim_avatar_default)
                    .override(300, 300)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.cir_icon.setImageBitmap(resource);
                        }
                    });

            ih.uname.setText("" + dataBean.getUserName());
            ih.title.setText("" + dataBean.getHelpTitle());
            ih.price_tv.setText(dataBean.getHelpMoney() + "元" + "/次");
            ih.textcontent.setText(dataBean.getHelpInfo());
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<User> oderuserList = Xutils.queryAll(mActivity.getApplication(), User.class);
                    if (oderuserList == null || oderuserList.size() == 0) {
                        Tools.redirectActivity(mActivity, LoginActivity.class);
                        return;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("helpId", dataBean.getHelpid());
                    Tools.redirectActivity(mActivity, MyselfHelpingOrderSingleActivity.class, map);
                }
            });
            ih.userinfo_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<User> oderuserList = Xutils.queryAll(mActivity.getApplication(), User.class);
                    if (oderuserList == null || oderuserList.size() == 0) {
                        Tools.redirectActivity(mActivity, LoginActivity.class);
                        return;
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("helpId", dataBean.getHelpid());
                    Tools.redirectActivity(mActivity, MyselfHelpingOrderSingleActivity.class, map);
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public CircleImageView cir_icon;
            public TextView title;
            public TextView price_tv;
            public TextView textcontent;
            public TextView uname;
            public Button userinfo_bt;

            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                uname = itemView.findViewById(R.id.uname);
                cir_icon = itemView.findViewById(R.id.cir_icon);
                title = itemView.findViewById(R.id.title);
                price_tv = itemView.findViewById(R.id.price_tv);
                textcontent = itemView.findViewById(R.id.textcontent);
                userinfo_bt = itemView.findViewById(R.id.userinfo_bt);
            }
        }

        public void initRefresh(List<HelpInfoDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<HelpInfoDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void deleteRow(int position) {
            dataBeen.remove(position);
            notifyDataSetChanged();
        }
    }


    public void query(int pagenow) {
        final List<User> userList = Xutils.queryAll(mActivity.getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            return;
        }
        User user = userList.get(0);
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("userId", user.getUserId() + "");
        Xutils.POST(HttpUrl.userneedhelpqueryuserid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson = new Gson();
                HelpInfoDomain domain = gson.fromJson(result, HelpInfoDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), mActivity));

                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow) {
        final List<User> userList = Xutils.queryAll(mActivity.getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            return;
        }
        lastloading = true;
        User user = userList.get(0);
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("userId", user.getUserId() + "");
        Xutils.POST(HttpUrl.userneedhelpqueryuserid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                lastloading = false;
                Gson gson = new Gson();
                HelpInfoDomain domain = gson.fromJson(result, HelpInfoDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), mActivity));

                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
                pulltofresh.loadmoreFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
